package cn.good.yan.config;

import cn.good.yan.config.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * 授权服务器配置
 *
 * @author shengren.yan
 * @create 2024/10/14
 */
@Configuration
// 启用授权服务配置
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder pw;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsServiceImpl userService;

    // ---- Redis刷新token  ----
//    @Autowired
//    @Qualifier("redistokenStore")  -- Redis存储到redis中
//    private TokenStore tokenStore;


    // ---- JWT刷新token  ----
    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    // JWT内存增强器
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    /**
     * 使用密码模式，需要配置
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(delegates);


//        super.configure(endpoints);
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService)
//                // Redis存储到redis中
//                .tokenStore(tokenStore);
                // 配置存储令牌策略
                .tokenStore(tokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                // 配置JWT内存增强器
                .tokenEnhancer(enhancerChain);
        ;
    }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
                // 配置client id
                .withClient("admin")
                // 配置client secret
                .secret(pw.encode("1122"))
                // 配置token的有效期，默认秒
                .accessTokenValiditySeconds(3600)
                // 配置刷新token的有效期，默认秒
                .refreshTokenValiditySeconds(864000)
                // 授权成功后跳转的页面
                .redirectUris("http://localhost:8090/login")
//                .redirectUris("http://baidu.com")
                // 配置申请的权限范围
                .scopes("all")
                // 自动授权，配置这个，代表跳转后，默认是授权的，不再提示授权选择页面
                .autoApprove(true)
                // 配置授权类型
                // 目前是 授权码模式 - authorization_code
//                .authorizedGrantTypes("authorization_code")
                // 配置密码秘书 password，上面的 授权码模式 需要注释
                // 可以配置多个 refresh_token 是刷新token，重写获取token
                .authorizedGrantTypes("password", "refresh_token", "authorization_code")
        ;

    }

    // 单点登录
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 获取秘钥需要申请认证，单点登录必须配置
        security.tokenKeyAccess("isAuthenticated()");
    }


}


